package com.atguigu.yygh.hosp.service.impl;

import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.hosp.repository.DepartmentRepository;
import com.atguigu.yygh.hosp.service.DepartmentService;
import com.atguigu.yygh.model.hosp.Department;
import com.atguigu.yygh.vo.hosp.DepartmentQueryVo;
import com.atguigu.yygh.vo.hosp.DepartmentVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DepartmentServiceImpl implements DepartmentService {
    @Autowired
    private DepartmentRepository departmentRepository;

    @Override
    public void save(Department department) {
        if (department==null){
            throw new YyghException(20001,"department数据参数错误");
        }
        //根据医院编号 和科室编号查  数据库是否有
        Department exitdepartment = departmentRepository
        .findDepartmentByHoscodeAndDepcode(department.getHoscode(),department.getDepcode());

        if (exitdepartment!=null){
            department.setId(exitdepartment.getId());
            department.setCreateTime(exitdepartment.getCreateTime());
            department.setUpdateTime(new Date());
            department.setIsDeleted(0);
            departmentRepository.save(department);
        }else {
            department.setCreateTime(new Date());
            department.setUpdateTime(new Date());
            department.setIsDeleted(0);
            departmentRepository.save(department);
        }


    }

    @Override
    public Page<Department> selectPage(int page, int limit, DepartmentQueryVo departmentQueryVo) {
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        //0为第一页
        Pageable pageable = PageRequest.of(page-1, limit, sort);

        Department department = new Department();
        BeanUtils.copyProperties(departmentQueryVo, department);
        department.setIsDeleted(0);

        //创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true); //改变默认大小写忽略方式：忽略大小写

        //创建实例
        Example<Department> example = Example.of(department, matcher);
        Page<Department> pages = departmentRepository.findAll(example, pageable);
        return pages;
    }

    @Override
    public void remove(String hoscode, String depcode) {
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        if(null != department) {
//            departmentRepository.deleteById(department.getId());
            department.setIsDeleted(1);
           departmentRepository.save(department);
        }
    }
    //根据医院编号查询所有科室
    @Override
    public List<DepartmentVo> findDeptTree(String hoscode) {
        List<DepartmentVo> result =new ArrayList<>();
        //1.根据医院编号查询所有科室
        Department department = new Department();
        department.setHoscode(hoscode);
        Example<Department> example = Example.of(department);
        //调用方法
        List<Department> allDepartmentList = departmentRepository.findAll(example);
        //2.1封装数据，按照要求的格式
        //根据大科室编号 进行分组操作 封装map集合
        //map集合 key： 分组大科室编号  value：小科室集合List<DepartmentVoSmall>
        Map<String, List<Department>> departmentMap =
                allDepartmentList.stream()
                        .collect(Collectors.groupingBy(Department::getBigcode));
        //2.2遍历分组map集合
        for (Map.Entry<String, List<Department>> entry : departmentMap.entrySet()) {
            //获取key值 ---大科室编号
            String bigCode = entry.getKey();
            //获取value值 --- 大科室编号下面所有的小科室集合
            List<Department> departmentListSmall = entry.getValue();

            //2.3封装大科室
            DepartmentVo departmentVoBig = new DepartmentVo();
            departmentVoBig.setDepname(departmentListSmall.get(0).getBigname());
            departmentVoBig.setDepcode(bigCode);

            //2.4封装小科室集合
             //封装大科室里面的所有小科室到list集合
            List<DepartmentVo> children = new ArrayList<>();
            //遍历分组之后，每个大科室下面的所有小科室集合
            for (Department department1 : departmentListSmall) {
              //把每个小科室 封装到departmentVoSmall对象中
                DepartmentVo departmentVoSmall= new DepartmentVo();
                departmentVoSmall.setDepcode(department1.getDepcode());
                departmentVoSmall.setDepname(department1.getDepname());
                //封装之后的小科室对象 放到小科室集合中
                children.add(departmentVoSmall);
            }

            //把封装好的小科室list集合放到departmentVoBig大科室对象中
            departmentVoBig.setChildren(children);
            //把多个大科室 封装进最终List集合中
            result.add(departmentVoBig);
        }
        return result;
    }
    //获取科室名称
    @Override
    public String getDepName(String depcode) {
      Department department =departmentRepository.findDepartmentByDepcode(depcode);
      return department.getDepname();

    }
}
